#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "sem.h"
#include <termios.h>
#include <fcntl.h>
#include <sys/stat.h>
#define SEND_OK 0xAA
void serial_init(int fd)
{
	struct termios options;
	tcgetattr(fd, &options);
	options.c_cflag |= ( CLOCAL | CREAD );
	options.c_cflag &= ~CSIZE;
	options.c_cflag &= ~CRTSCTS;
	options.c_cflag |= CS8;
	options.c_cflag &= ~CSTOPB;
	options.c_iflag |= IGNPAR;
	options.c_iflag &= ~(ICRNL | IXON);
	options.c_oflag = 0;
	options.c_lflag = 0;

	cfsetispeed(&options, B115200);
	cfsetospeed(&options, B115200);
	tcsetattr(fd,TCSANOW,&options);
}

typedef struct
{
	uint8_t head[3];	 //标识位st:
	uint8_t type;		 //数据类型
	uint8_t snum;		 //仓库编号
	uint8_t temp[2];	 //温度	
	uint8_t hum[2];		 //湿度
	uint8_t x;			 //三轴信息
	uint8_t y;			 
	uint8_t z;			 
	uint32_t ill;		 //光照
	uint32_t bet;		 //电池电量
	uint32_t adc; 		 //电位器信息
}sendEnv;	

int main (int argc, char *argv[])
{
	sendEnv myEnv = {};
	int dev_uart_fd;

	
	if((dev_uart_fd = open("/dev/ttyUSB0", O_RDWR)) < 0)
	{
		perror("uart uart err");
		return -1;
	}
	serial_init(dev_uart_fd);
	while(1)
	{
		read(dev_uart_fd, &myEnv, sizeof(myEnv));
	
 }

	key_t key;
	sendEnv *pmyEnv;
	int shmid;
	key = ftok("/",'a');
	if(key < 0)
	{
		perror("fail to ftok");
		exit(-1);
	}

	shmid = shmget(key, sizeof(myEnv),IPC_CREAT | IPC_EXCL | 0777);
	if(shmid < 0)
	{
		if (errno == EEXIST)
		{
			shmid = shmget(key,0,0);
		}
		else
		{
			perror("fail to shmget");
			exit(-1);
		}
	}
		if((pmyEnv = (sendEnv *)shmat(shmid,NULL,0)) ==(sendEnv *)-1 )
		{
			perror("fail to shmmat");
			exit(-1);
		}
/*
		pmyEnv->head[0] = myEnv.head[0];
		pmyEnv->head[1] = myEnv.head[1];
		pmyEnv->head[2] = myEnv.head[2];
		pmyEnv->type = myEnv.type;
		pmyEnv->snum = myEnv.snum;
		pmyEnv->temp[0] = myEnv.temp[0];
		pmyEnv->temp[1] =myEnv.temp[1];
		pmyEnv->hum[0] = myEnv.hum[0];
		pmyEnv->hum[1] = myEnv.hum[1];
		pmyEnv->x = myEnv.x;
		pmyEnv->y = myEnv.y;
		pmyEnv->z = myEnv.z;
		pmyEnv->ill = myEnv.ill;
		pmyEnv->bet = myEnv.bet;
		pmyEnv->adc = myEnv.adc;
*/
		while(1)
		{
		pmyEnv->head[0] = myEnv.head[0];
		pmyEnv->head[1] = myEnv.head[1];
		pmyEnv->head[2] = myEnv.head[2];
		pmyEnv->type = myEnv.type;
		pmyEnv->snum = 23;
		pmyEnv->temp[0] = 23;
		pmyEnv->temp[1] = 44;
		pmyEnv->hum[0] = 32;
		pmyEnv->hum[1] = 12;
		pmyEnv->x = 32;
		pmyEnv->y = 33;
		pmyEnv->z = 22;
		pmyEnv->ill = 11;
		pmyEnv->bet = 22;
		pmyEnv->adc = 12;
		sleep(2);
		}
		return 0;
}
